let gulp = require("gulp");
let connect = require("gulp-connect");
let proxy = require('http-proxy-middleware')
var sass = require('gulp-sass');
sass.compiler = require('node-sass');

let {
      paths,
      proxyList
} = require("./gulp.config");

function devStyles() {
      return gulp.src(paths.styles.src)
            .pipe(sass().on('error', sass.logError))
            .pipe(gulp.dest(paths.styles.dist))
            .pipe(connect.reload());
}

function devScripts() {
      return gulp.src(paths.scripts.src)
            .pipe(gulp.dest(paths.scripts.dist))
            .pipe(connect.reload());
}

function devHtml() {
      return gulp.src(paths.html.src)
            .pipe(gulp.dest(paths.html.dist))
            .pipe(connect.reload());
}

function devIndex() {
      return gulp.src(paths.index.src)
            .pipe(gulp.dest(paths.index.dist))
            .pipe(connect.reload());
}

function configs() {
      return gulp.src(paths.config.src)
            .pipe(gulp.dest(paths.config.dist));
}

function json() {
      return gulp.src(paths.json.src)
            .pipe(gulp.dest(paths.json.dist));
}

function useconnect() {
      connect.server({
            root: "./dist",
            port: 8888,
            livereload: true,
            middleware: function (connect, opt) {
                  let arr = [];
                  for (let attr in proxyList) {
                        arr.push(proxy(attr, proxyList[attr]));
                  }
                  return arr;
            }
      });
}

function watch() {
      gulp.watch(paths.styles.src, devStyles);
      gulp.watch(paths.scripts.src, devScripts);
      gulp.watch(paths.html.src, devHtml);
}

let dev = gulp.series(devHtml, json,configs, devIndex, devScripts, devStyles, gulp.parallel(useconnect, watch));

module.exports = dev;